<template>
  <div class="bookNote-list-content">
    <iv-row>
      <iv-col :xs="24" :sm="24" :md="24" :lg="17">
        <!--<div id="edtiText" style="margin-top: 30px">
          <textarea id="editor1" rows="10" cols="80" ></textarea>
        </div>-->
        <iv-form ref="article" :model="article" :label-width="80">
          <iv-input name='id' v-model="article.id" v-show="false"/>
          <iv-row>
            <iv-col span="5">
              <iv-formItem label="选择封面：">
                <iv-upload
                  action=""
                  :format="['jpg','jpeg','png', 'gif']"
                  :max-size="10240"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  :before-upload="handleBeforeUpload">
                  <iv-tooltip content="重新上传将覆盖默认封面" placement="top">
                    <iv-button icon="ios-cloud-upload-outline">上传封面</iv-button>
                  </iv-tooltip>
                  <span v-if="article.articleHeadPic !=='' ">上传成功</span>
                </iv-upload>
              </iv-formItem>
            </iv-col>
            <iv-col span="6" offset="2">
              <img class="live-cover" :src="article.articleHeadPic" style=" width:140px;height: 90px;">
            </iv-col>
          </iv-row>
          <iv-formItem label="文章标题：">
            <iv-input placeholder="请填写文章标题..." :maxlength="40" v-model="article.articleName"></iv-input>
          </iv-formItem>
          <iv-formItem label="文章简介：">
            <iv-input placeholder="请填写文章简介..." :maxlength="100" v-model="article.articleRemark"></iv-input>
          </iv-formItem>
          <iv-formItem label="是否公开：">
            <iv-switch :maxlength="50" v-model="article.disclosure"></iv-switch>
          </iv-formItem>
          <iv-formItem label="文章内容：">
            <mavon-editor ref=md
                          style="height:100%"
                          @imgAdd="imgAdd"
                          v-model="article.articleContent"
                          :toolbars="toolbars"
                          @change="mavonChangeHandle">
              <!-- 引用视频链接的自定义按钮 -->
              <template v-slot:left-toolbar-after>
                <!--点击按钮触发的事件是打开表单对话框-->
                <iv-button type="text" @click="uploadFile" aria-hidden="true" class="op-icon fa" title="插入视频资源">
                  <iv-icon type="ios-cloud-upload"/>
                </iv-button>
              </template>
            </mavon-editor>
            <!-- 在这里放一个隐藏的input，用来选择文件 -->
            <input ref="uploadInput" style="display: none" type="file" @change="uploadFileChange">
          </iv-formItem>

          <iv-formItem label="文章标签：">
            <iv-tag v-for="item in countTags" :key="item" :name="item" closable @on-close="handleClose">{{
                item
              }}
            </iv-tag>
            <iv-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </iv-input>
            <iv-button v-else size="small" type="dashed" icon="ios-add" @click="showInput">+ 添加标签</iv-button>
          </iv-formItem>

<!--          <iv-formItem label="文章类型：">-->
<!--            <iv-select v-model="article.articleType" style="width: 200px;">-->
<!--              <iv-option v-for="item in statusArr" :value="item.key" :key="item.key">{{ item.label }}</iv-option>-->
<!--            </iv-select>-->
<!--          </iv-formItem>-->
          <iv-formItem label="文章类型：">
            <iv-select v-model="article.articleType" style="width: 200px;">
              <i-option value="1001">技术交流</i-option>
              <i-option value="1002">经验杂谈</i-option>
              <i-option value="1003">随笔书写</i-option>
            </iv-select>
          </iv-formItem>

          <iv-formItem label="文章备注：">
            <iv-input type="textarea" placeholder="请填写文章备注..." v-model="article.remark" :maxlength="100"></iv-input>
          </iv-formItem>

          <iv-formItem label="选择附件：">
            <iv-upload
              action=""
              :format="['zip','doc','xls','ppt','txt','pdf','mp3','mp4']"
              :max-size="51200"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSizeFile"
              :before-upload="handleUpload">
              <iv-button icon="ios-cloud-upload-outline">选择附件</iv-button>
              <span v-if="article.enclosure !=='' ">上传成功</span>
            </iv-upload>

          </iv-formItem>
        </iv-form>

        <iv-button type="error" @click="saveArticle">发表文章</iv-button>
      </iv-col>
      <iv-col :xs="0" :sm="0" :md="0" :lg="7">
        <div class="layout-right">
          <recommend></recommend>
          <tag-wall style="margin-top: 15px;"></tag-wall>
        </div>
      </iv-col>
    </iv-row>
  </div>
</template>

<script type="text/ecmascript-6">
import Recommend from '@/components/views/Recommend'
import TagWall from '@/components/views/TagWall'
import BrowseMore from '@/components/views/BrowseMore'
// eslint-disable-next-line no-unused-vars
import merge from 'lodash/merge' // 合并对象工具
import axios from 'axios'
import marked from 'marked'

export default {
  data() {
    return {
      //tag参数
      countTags: [],
      inputVisible: false,
      inputValue: '',
      contentxt: "",
      statusArr: [
        {
          key: '1001',
          label: '技术交流'
        }, {
          key: '1002',
          label: '经验杂谈'
        }, {
          key: '01003',
          label: '随笔书写'
        }],
      article: {
        recommend: false,
        disclosure: true,
        Tag: [],
        articleHeadPic: 'https://oss.yuuuu.vip/qiyuan/image/logo.png',
        articleName: '',
        articleRemark: '',
        articleType: '',
        enclosure: '',
        remark: ''
      },
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: false, // 标记
        superscript: false, // 上角标
        subscript: false, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: false, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: false, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: false, // 下一步
        trash: false, // 清空
        save: false, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: false, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
        boxShadow: false
      }
    }
  },
  created: function () {
    let param = {}
    param.latest = true
    // 初始化方法 判断是否登录
    let manager = JSON.parse(sessionStorage.getItem('currentManager'))
    if (manager === null){
      this.$Message.warning('请登录');
      this.$router.push({path: "/login"});
    }
  },
  methods: {
    //标签部分
    handleClose(tag) {
      this.countTags.splice(this.countTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      if (this.countTags && this.countTags.length >= 5) {
        this.$Message.warning('最多添加5个标签');
        return;
      }
      let inputValue = this.inputValue;
      if (inputValue) {
        this.countTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },

    // 上传图片
    imgAdd(pos, file) {
      let formData = new FormData()
      formData.append('file', file)
      axios({
        url: this.$http.adornUrl('/oss/upload'),
        method: 'post',
        data: formData,
        headers: {'Content-Type': 'multipart/form-data'}
      }).then((data) => {
        // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
        /**
         * $vm 指为mavonEditor实例，可以通过如下两种方式获取
         * 1.  通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
         * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
         */
          if (data.data.status === 0) {
            if (data.data.result.msg.intranetStatus === '1'){
              this.$refs.md.$img2Url(pos, data.data.result.msg.url)
            }else{
              this.$refs.md.$img2Url(pos, data.data.result.msg.intranetUrl)
            }
          }
      })
    },


    handleFormatError(file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: '文件 ' + file.name + ' 格式不正确，请上传格式的图片。'
      })
    },

    handleMaxSize(file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件 ' + file.name + ' 太大，不能超过 10M。'
      })
    },
    handleMaxSizeFile(file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件 ' + file.name + ' 太大，不能超过 50M。'
      })
    },

    handleUpload(file) {
      let formData = new FormData()
      formData.append('file', file)
      axios({
        url: this.$http.adornUrl('/oss/upload'),
        method: 'post',
        data: formData,
        headers: {'Content-Type': 'multipart/form-data'}
      }).then((data) => {
        if (data.data.status === 0) {
          if (data.data.result.msg.intranetStatus === '1'){
            this.article.enclosure = data.data.result.msg.url
          }else{
            this.article.enclosure = data.data.result.msg.intranetUrl
          }
          this.$Message.success('封面上传成功')
        }
      })
    },

    handleBeforeUpload(file) {
      let formData = new FormData()
      formData.append('file', file)
      axios({
        url: this.$http.adornUrl('/oss/upload'),
        method: 'post',
        data: formData,
        headers: {'Content-Type': 'multipart/form-data'}
      }).then((data) => {
        if (data.data.status === 0) {
          if (data.data.result.msg.intranetStatus === '1'){
            this.article.articleHeadPic = data.data.result.msg.url
          }else{
            this.article.articleHeadPic = data.data.result.msg.intranetUrl
          }
          this.$Message.success('封面上传成功')
        }
      })
    },

    /** 自定义附件**/
    // 这是我们自定义的按钮触发的方法，这里也可以在自定义其他功能时做一些其他操作。
    uploadFile() {
      // 通过ref找到隐藏的input标签，触发它的点击方法
      this.$refs.uploadInput.click()
    },
    // 监听input获取文件的状态
    uploadFileChange(e) {
      // 获取到input选取的文件
      const file = e.target.files[0]
      // 创建form格式的数据，将文件放入form中，logo是与后台定义的字段
      let formData = new FormData()
      formData.append('file', file)
      //组装
      let linkFrame = '';
      let linkFrameStart = "<div align=center><video width=100% height='430px' controls='controls' src='"
      let linkFrameEnd = "' frameborder=0 'allowfullscreen'></video></div>"
      // 创建一个div盒子，为提取src做准备
      var box = document.createElement("div");

      axios({
        url: this.$http.adornUrl('/oss/upload'),
        method: 'post',
        data: formData,
        headers: {'Content-Type': 'multipart/form-data'}
      }).then((data) => {
        if (data.data.status === 0) {
          let url;
          url = data.data.result.msg.url
          // if (data.data.result.msg.intranetStatus === '1'){
          //   url = data.data.result.msg.url;
          // }else {
          //   url = data.data.result.msg.intranetUrl;
          // }
          box.innerHTML = url;
          linkFrame = linkFrameStart + url + linkFrameEnd;
          // 获取文本域中当前光标起始位置、结束位置以及滚动条位置（滚动条位置我认为没有必要，如有需要可以自己取消注释）
          let textarea = document.getElementsByClassName("auto-textarea-input")[0];
          let posStart = textarea.selectionStart;
          let posEnd = textarea.selectionEnd;
          // 获取文本域中未选中的的前半部分和后半部分，以被选中内容起始和结束位置做分割点
          let subStart = this.$refs.md.d_value.substring(0, posStart);
          let subEnd = this.$refs.md.d_value.substring(posEnd, this.$refs.md.d_value.length);
          // 拼接并替换文本域内容
          this.$refs.md.d_value = subStart + '\n' + linkFrame + '\n' + subEnd;

          // // 这里获取到的是mavon编辑器实例，上面挂载着很多方法
          // const $vm = this.$refs.md
          // // 将文件名与文件路径插入当前光标位置，这是mavon-editor 内置的方法
          // $vm.insertText($vm.getTextareaDom(),
          //   {
          //     prefix: `[${file.name}](${data.data.result.msg.url})`,
          //     subfix: '',
          //     str: ''
          //   })
          this.$Message.success('上传成功')
        }
      })
    },

    // 保存文章
    saveArticle: function () {
      let tag = ""
      for (let i = 0; i < this.countTags.length; i++) {
        // eslint-disable-next-line no-unused-vars
        tag += this.countTags[i] + ","
      }
      this.article.articleTag = tag
      this.article.managerId = this.$route.params.managerId
      let article = this.article
      article.articleContent = this.contentxt
      if (article.articleHeadPic === null || article.articleHeadPic === '') {
        this.$Message.error('请上传封面')
        return
      } else if (article.articleName === null || article.articleName === '') {
        this.$Message.error('请输入文章名称')
        return
      } else if (article.articleContent === null || article.articleContent === '') {
        this.$Message.error('请输入文章内容')
        return
      } else if (article.articleTag === null || article.articleTag === '') {
        this.$Message.error('请输入文章标签')
        return
      }
      this.$http({
        url: this.$http.adornUrl(`/article/save`),
        method: 'post',
        data: this.$http.adornData(article),
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        }
      }).then(({data}) => {
        if (data && data.status === 0) {
          this.$Message.success('发表成功')
          // 关闭当前标签
          this.$emit('closeCurrentTabs')
          // 跳转到list
          this.$router.push('/')
        } else {
          this.$Message.error(data.errorMsg)
          this.$router.push('/login')
        }
      })
    },
    mavonChangeHandle(context, html) {
      this.contentxt = html
      this.article.articleContent = marked(html)
    }

  },
  components: {
    'recommend': Recommend,
    'tag-wall': TagWall,
    'browse-more': BrowseMore
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
.bookNote-list-content
  width auto
  @media only screen and (max-width: 768px)
    margin 5px 5px 0 5px
  @media screen and (min-width: 768px)
    margin 10px 10px 0 10px
  @media screen and (min-width: 992px)
    margin 15px 35px 0 35px
  @media screen and (min-width: 1200px)
    width 1200px
    margin 15px auto 0
    margin-bottom 200px

  .layout-left, .layout-right
    padding 0
    @media only screen and (max-width: 768px)
      padding 0
    @media screen and (min-width: 768px)
      padding 0
    @media screen and (min-width: 992px)
      padding 0 10px
    @media screen and (min-width: 1200px)
      padding 0 10px

.iv-tag + .iv-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 20px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 80px;
  margin-left: 0px;
}
</style>
